package tgc.rj.zz.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.DataGridUtils;
import tgc.rj.zz.entity.Invoice;
import tgc.rj.zz.entity.Journal;
import tgc.rj.zz.entity.Lessee;
import tgc.rj.zz.entity.SysUser;
import tgc.rj.zz.entity.User;
import tgc.rj.zz.form.DzfpForm;
import tgc.rj.zz.form.InvoiceForm;
import tgc.rj.zz.security.UserUtils;
import tgc.rj.zz.service.InvoiceService;
import tgc.rj.zz.service.JournalService;
import tgc.rj.zz.service.LesseeService;

@Controller
@RequestMapping(value="invoice")
public class InvoiceController {
	@Autowired
	private InvoiceService invoiceService;
	@Autowired
	private LesseeService lesseeService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private JournalService service;
	
	/**
	 * 电子发票管理
	 * @return
	 */
	@RequestMapping(value="all_dzdp")
	public String all_dzdp(ModelMap map) {
		List<Lessee> zhs = lesseeService.findAll();
		map.put("zhs", zhs);
		return "user/dzfp";
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(InvoiceForm form) {
		Pageable pageable = form.buildPageable();
		Page<Invoice> page = null;
		if(form.getId() == null) {
			page = invoiceService.findAll(pageable);			
		}else {
			page = invoiceService.findAll(form.buildSpes(), pageable);
		}
		HashMap<String , Object> result = DataGridUtils.getPageResult(page);
		
		
		return result;
	}
	/**
	 * 新增电子发票
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/saveDzfp")
	@ResponseBody
	public Object saveDzfp(DzfpForm form) {
		Invoice model=new Invoice();
		Lessee id = lesseeService.findById(form.getLess());
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			model.setDate(sf.parse(form.getDate()));
			model.setEndDate(sf.parse(form.getEndDate()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		BeanUtils.copyProperties(form, model);
		model.setLessee(id);
		invoiceService.save(model);
		
		SysUser user = userUtils.getUser();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String date = df.format(new Date());
		Journal journal = new Journal();
		journal.setDate(date);
		journal.setUsername(user.getUsername());
		journal.setOperationName("新增发票");
		service.save(journal);
		return "ok";
		
	}
	
	
}
